package com.tgpay.cdiot.controller;

import com.tgpay.cdiot.service.UpstreamApiService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.Map;

@RestController
@RequestMapping("/api")
@CrossOrigin(origins = "*")
public class DeviceController {

    @Autowired
    private UpstreamApiService upstreamApiService;

    /**
     * 获取设备列表
     */
    @GetMapping("/devices")
    public ResponseEntity<Object> getDevices() {
        try {
            Object result = upstreamApiService.getDevices();
            return ResponseEntity.ok(result);
        } catch (Exception e) {
            return ResponseEntity.status(500).body(Map.of(
                "code", 500,
                "message", "获取设备列表失败: " + e.getMessage(),
                "data", null
            ));
        }
    }

    /**
     * 获取设备详情
     */
    @GetMapping("/devices/{imei}")
    public ResponseEntity<Object> getDeviceDetail(@PathVariable String imei) {
        try {
            Object result = upstreamApiService.getDeviceDetail(imei);
            return ResponseEntity.ok(result);
        } catch (Exception e) {
            return ResponseEntity.status(500).body(Map.of(
                "code", 500,
                "message", "获取设备详情失败: " + e.getMessage(),
                "data", null
            ));
        }
    }

    /**
     * 启动充电
     */
    @PostMapping("/devices/{imei}/ports/{portId}/start")
    public ResponseEntity<Object> startCharging(
            @PathVariable String imei,
            @PathVariable String portId,
            @RequestBody Map<String, Object> requestBody) {
        try {
            // 设置默认值
            if (!requestBody.containsKey("chargeType")) {
                requestBody.put("chargeType", 3); // 默认按时间充电
            }
            if (!requestBody.containsKey("chargeParam")) {
                requestBody.put("chargeParam", 3600); // 默认1小时（3600秒）
            }
            if (!requestBody.containsKey("startMethod")) {
                requestBody.put("startMethod", 1); // 默认扫码启动
            }
            if (!requestBody.containsKey("cardNumber")) {
                requestBody.put("cardNumber", 0);
            }
            if (!requestBody.containsKey("availableAmount")) {
                requestBody.put("availableAmount", 10000); // 默认100元
            }
            
            // 处理充电参数：如果是按时间充电(chargeType=3)且参数小于等于1440（24小时），
            // 则认为传入的是分钟数，需要转换为秒数
            Object chargeType = requestBody.get("chargeType");
            Object chargeParam = requestBody.get("chargeParam");
            
            if (chargeType != null && chargeParam != null) {
                int type = Integer.parseInt(chargeType.toString());
                int param = Integer.parseInt(chargeParam.toString());
                if (type == 3 && param <= 1440) { // 按时间充电且参数<=1440（可能是分钟）
                    int seconds = param * 60; // 转换为秒数
                    requestBody.put("chargeParam", seconds);
                    System.out.println("按时间充电：将" + param + "分钟转换为" + seconds + "秒");
                }
            }
            
            Object result = upstreamApiService.startCharging(imei, portId, requestBody);
            return ResponseEntity.ok(result);
        } catch (Exception e) {
            return ResponseEntity.status(500).body(Map.of(
                "code", 500,
                "message", "启动充电失败: " + e.getMessage(),
                "data", null
            ));
        }
    }

    /**
     * 停止充电
     */
    @PostMapping("/devices/{imei}/ports/{portId}/stop")
    public ResponseEntity<Object> stopCharging(
            @PathVariable String imei,
            @PathVariable String portId,
            @RequestBody Map<String, Object> requestBody) {
        try {
            Object result = upstreamApiService.stopCharging(imei, portId, requestBody);
            return ResponseEntity.ok(result);
        } catch (Exception e) {
            return ResponseEntity.status(500).body(Map.of(
                "code", 500,
                "message", "停止充电失败: " + e.getMessage(),
                "data", null
            ));
        }
    }

    /**
     * 获取充电状态
     */
    @GetMapping("/devices/{imei}/ports/{portId}/status")
    public ResponseEntity<Object> getChargingStatus(
            @PathVariable String imei,
            @PathVariable String portId) {
        try {
            Object result = upstreamApiService.getChargingStatus(imei, portId);
            return ResponseEntity.ok(result);
        } catch (Exception e) {
            return ResponseEntity.status(500).body(Map.of(
                "code", 500,
                "message", "获取充电状态失败: " + e.getMessage(),
                "data", null
            ));
        }
    }
}